package leetcode;

public class String_to_integer_atoi {

}

class Solution8 {
    public int myAtoi(String str) {
    	int length = str.length();
    	int start = -1, end = length;
    	int flag = 1;
    	for (int i = 0; i < length; i++) {
    		if (str.charAt(i) == ' ') {
				continue;
			}
			if (str.charAt(i) == '-'|| str.charAt(i) == '+' || (str.charAt(i) <= '9' && str.charAt(i) >= '0')) {
				start = i;
				if (str.charAt(i) == '-') {
					flag = -1;
					if (i+1 >= length || str.charAt(i+1) > '9' || str.charAt(i+1) < '0') flag = 0;
				}
				if (str.charAt(i) == '+') {
					flag = 1;
					if (i+1 >= length || str.charAt(i+1) > '9' || str.charAt(i+1) < '0') flag = 0;
				}
				break;
			}
			break;
		}
    	for (int i = start + 1; i < length; i++) {
			if (str.charAt(i) > '9' || str.charAt(i) < '0' ) {
				end = i;
				break;
			}
		}
    	try {
    		if(start >= 0) return Integer.valueOf(str.substring(start, end));
		} catch (NumberFormatException e) {
			// TODO: handle exception
			if (flag > 0) return Integer.MAX_VALUE;
			if (flag < 0) return Integer.MIN_VALUE;
		}
    	return 0;
    }
}
